<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 00:33:05
 * @LastEditTime: 2023-11-03 15:55:54
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: BOM成品工艺
 */

namespace App\Models;

use App\Traits\AutoCodeTrait;
use App\Traits\MaterialTrait;
use App\Repositories\FinanceVoucherRepository;
use App\Traits\AttachmentTrait;
use App\Traits\VoucherTrait;

class CustomerStorage extends BaseModel
    {

    public $ACSign = "CUSTOMER_STORAGE";
    public function details()
        {
        return $this->hasMany(CustomerStorageDetail::class, "main_id");
        }
    use AutoCodeTrait;
    use AttachmentTrait;
    use MaterialTrait;
    use VoucherTrait;
    public $timestamps = true;
    public $table = "sys_customer_receive";
    protected $guarded = [];
    //附件
    public $attachmentkey = "code";

    public function salesman()
        {
        return $this->belongsTo(Employee::class);
        }
    /**
     * 编号所用的字段
     *
     * @var string
     */
    protected $ACCode = 'code';


    public function department()
        {
        return $this->belongsTo(Department::class);
        }
    public function status()
        {
        return $this->belongsTo(Dic::class, "status_id", "key")->where(function ($q)
            {
            $q->where("code", 'status_with_finance');
            });
        }
    public function check_unit()
        {
        return $this->belongsTo(Dic::class, "check_unit_id", "key")->where(function ($q)
            {
            $q->where("code", 'unitMM');
            });
        }
    public function finance($order = null)
        {
        $v = $order ?? $this;

        if ($v->status_id == 2)
            return $v->voucher;

        if ($v->status_id != 1) {
            fail("单据非审核状态！，无法财审！");
            }

        $details       = [];
        $debit_subject = $credit_subject = null;
        //客户到货不做凭证
        $need_voucher = true;
        //摘要
        $summary = $v->finance_remark;
        //采购入库，采购退货
        if (in_array($v->instorage_way_id, [1, 4])) {

            //采购折价
            if ($v->complaint_id == 4) {
                //营业外收入/其他
                $credit_subject = 530199;
                //贷应付账款 2202 
                $debit_subject = 2202;
                $summary .= "折价优惠";
                }
            else {
                //借库存商品1405 
                $debit_subject = 1405;
                //贷应付账款 2202 
                $credit_subject = 2202;
                $summary .= $v->instorage_way_id == 1 ? "采购" : "退货";
                }


            }
        else if ($v->instorage_way_id == 3) {

            // 发货：月末计算
            // 借:委托加工物资-原材料 140801
            // 贷:原材料/库存商品 1405

            // 加工：
            // 借:委托加工物资-加工费 140802
            // 贷:应付账款 2202 


            // 收回时:月末计算
            // 借:库存商品(或其它)
            // 贷:委托加工物资-原材料 140801
            // 贷:委托加工物资-加工费 140802

            //借 委托加工物资-加工费 140802
            $debit_subject = 140802;
            //贷 应付账款 2202
            $credit_subject = 2202;
            $summary .= "委外加工费";
            }
        else {
            $need_voucher = false;
            }

        //借方分录 
        $v->details->map(function ($v) use ($debit_subject, &$details, $credit_subject, $summary, $need_voucher)
            {
            fauditSave($v);
            if ($need_voucher) {
                $merge_Data             = $v->toArray();
                $merge_Data['quantity'] = $v->quantity;
                $merge_Data['price']    = $v->se_price;
                $details[]              = FinanceVoucherRepository::mergeVoucher($debit_subject, $summary, $v['se_amount'], 0, $merge_Data);
                $details[]              = FinanceVoucherRepository::mergeVoucher($credit_subject, $summary, 0, $v['se_amount'], $merge_Data);
                }
            })->toArray();
        //审核
        fauditSave($v);
        $voucher = null;
        if ($need_voucher) {
            //贷方分录  
            $voucher = FinanceVoucherRepository::CreateVoucher($v->billdate ?? $v->created_at, 1, $details, $v, $v->voucher?->id);
            //创建凭证
            $voucher = FinanceVoucherRepository::auditVoucher($voucher);
            }
        //返回凭证
        return $voucher;
        }
    public function nofinance($order = null)
        {
        $v = $order ?? $this;
        if ($v->status_id == 1)
            return $v->voucher;
        if ($v->status_id != 2) {
            fail("非财审状态！，无法取消财审！");
            }
        if (($v->voucher?->status_id ?? 0) != 0) {
            fail("凭证【{$v->voucher->code}】已记账！ 操作失败！");
            }
        $v->details->filter(function ($v)
            {
            fauditSave($v, false);
            });

        return fauditSave($v, false);

        }

    public function inside_barcode()
        {
        return $this->belongsTo(Barcode::class);
        }
    public function outside_barcode()
        {
        return $this->belongsTo(Barcode::class);
        }
    }